package repository

import (
	"gorm.io/gorm"
	"shyxy-model-agent/common/cache/lru"
	"shyxy-model-agent/core/model"
)

type grpcInstanceRepository struct {
	*BaseRepository
}

func NewGrpcInstanceRepository(db *gorm.DB) GrpcInstanceRepository {
	return &grpcInstanceRepository{
		BaseRepository: NewBaseRepository(db),
	}
}

func (gir *grpcInstanceRepository) Create(instance *model.GrpcInstance) error {
	return gir.GetDB().Create(instance).Error
}

func (gir *grpcInstanceRepository) FindListByStatusAndModelName(modelName string, status ...string) ([]*model.GrpcInstance, error) {
	var instances []*model.GrpcInstance
	query := gir.GetDB().Where("model_name = ?", modelName)
	if len(status) > 0 {
		query = query.Where("status IN ?", status)
	}
	return instances, query.Find(&instances).Error
}

type cachedGrpcInstanceRepository struct {
	*BaseCachedRepository
}

func (cgir *cachedGrpcInstanceRepository) CachedRepository() {}

func NewCachedGrpcInstanceRepository(db *gorm.DB, cache *lru.LRU) GrpcInstanceRepository {
	return &cachedGrpcInstanceRepository{
		BaseCachedRepository: NewBaseCachedRepository(db, cache, "grpc_instance"),
	}
}

func (cgir *cachedGrpcInstanceRepository) Create(instance *model.GrpcInstance) error {
	return (&grpcInstanceRepository{BaseRepository: NewBaseRepository(cgir.GetDB())}).Create(instance)
}

func (cgir *cachedGrpcInstanceRepository) FindListByStatusAndModelName(modelName string, status ...string) ([]*model.GrpcInstance, error) {
	return (&grpcInstanceRepository{BaseRepository: NewBaseRepository(cgir.GetDB())}).FindListByStatusAndModelName(modelName, status...)
}

func NewGrpcInstanceRepositoryWithCache(db *gorm.DB, cache *lru.LRU) GrpcInstanceRepository {
	if cache != nil {
		return NewCachedGrpcInstanceRepository(db, cache)
	}
	return NewGrpcInstanceRepository(db)
}
